package com.example.student.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.student.dao.UserDao;
import com.example.student.dao.impl.UserDaoImpl;
import com.example.student.entity.User;
import com.example.student.service.UserService;
import com.example.student.util.Pager;

import java.util.List;
import java.util.Objects;

/**
 * @author TonySong
 * @date 2025/8/7 0007
 * @time 19:26
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao =new UserDaoImpl();
    @Override
    public List<User> findAll() {
        return userDao.findAll(UserDao.FIND_USERS);
    }

    @Override
    public Pager<User> pageUsers(String currentPage,Integer pagesize) {
        return this.userDao.pagelist(UserDao.PAGE_USERS,currentPage,pagesize);
    }

    @Override
    public boolean delete(int parseInt) {
        return this.userDao.delete(UserDao.DELETE_USER,parseInt) > 0;
    }

    @Override
    public boolean add(User user) {
        if(Objects.isNull(user.getAvatar()) || StrUtil.isBlank(user.getAvatar())) {
            return this.userDao.save(UserDao.INSERT_USER, user.getUsername(), user.getPassword()) > 0;
        }
        return this.userDao.save(UserDao.INSERT_USER_AVATAR,user.getUsername(),user.getPassword(),user.getAvatar())>0;
    }

    @Override
    public User findUserById(int id) {
        return this.userDao.findObject(UserDao.FIND_USER,id);
    }

    @Override
    public boolean update(User user) {
        if(user.getAvatar()==null || StrUtil.isBlank(user.getAvatar())) {
            return this.userDao.update(UserDao.UPDATE_USER, user.getUsername(), user.getPassword(), user.getId()) > 0;
        }
        return this.userDao.update(UserDao.UPDATE_USER_AVATAR,user.getUsername(),user.getPassword(),user.getAvatar(),user.getId())> 0;
    }

    @Override
    public User login(User user) {
      return   this.userDao.findObject(UserDao.LOGIN_USER,new String[]{user.getUsername(),user.getPassword()});
    }

    @Override
    public boolean hasUsername(String username) {
        return this.userDao.executeScalre(UserDao.HAS_USERNAME,username)>=1;
    }
}
